package com.github.data_manage.controller.websocket

import com.github.data_manage.config.BeanConfig
import jakarta.websocket.server.ServerEndpoint
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import org.springframework.web.socket.CloseStatus
import org.springframework.web.socket.TextMessage
import org.springframework.web.socket.WebSocketSession
import org.springframework.web.socket.handler.TextWebSocketHandler
import java.util.concurrent.ConcurrentHashMap


/**
 *
 * @author CHN
 * @since 2021/5/18
 */
@Component
open class FundImportStatusHandler : TextWebSocketHandler(){

    companion object {
        val log: Logger = LoggerFactory.getLogger(FundImportStatusHandler::class.java)

        val sessionMap = ConcurrentHashMap<String, WebSocketSession>()

        fun isSendAble(): Boolean = sessionMap.isNotEmpty()

        fun sendInfoMessage(code: String,value: Any) {
//            sessionMap[code]?.sendMessage(
//                TextMessage(
//                    BeanConfig.objectMapper.writeValueAsString(
//                        mapOf(
//                            Pair("value", value)
//                        )
//                    )
//                )
//            )
        }
    }


    override fun afterConnectionEstablished(session: WebSocketSession) {
        val codes = session.uri!!.query
        if (codes.isNullOrEmpty()) {
            session.sendMessage(
                TextMessage(BeanConfig.objectMapper.writeValueAsString(
                    mapOf(
                        Pair("value", "链接唯一标识不能为空")
                    )
                ))
            )
            return
        }
        for (code in codes.split("&")) {
            if (code.contains("code")) {
                sessionMap[code.split("=")[1]] = session
            }
        }
    }

    override fun afterConnectionClosed(session: WebSocketSession, status: CloseStatus) {
        for (entry in sessionMap) {
            if (entry.value.id == session.id) {
                sessionMap.remove(entry.key)
                return
            }
        }
    }
}
